#include<cstdio>
#include<unistd.h>
#include<iostream>
#include<sys/types.h>
#include<cstdlib>
#include <stdlib.h>
#include<cstring>
#define N 2
#define NUM 1024
using namespace std;

//child
void writer(int wfd){
    string s="hello, I am child";
    pid_t self =getpid();
    int number = 0;
    
    char buffer[NUM];
    int num1=1;
    while(num1--){
        buffer[0]=0;
        snprintf(buffer,sizeof(buffer),"%s-%d-%d\n",s.c_str(),self,number++);//"%s-%d-%d\n"再加上\0传递赋值给buffer
        // cout<< buffer <<endl;
        write(wfd,buffer,strlen(buffer));//写入文件时，不带\0        
    }
}

void reader(int rfd){
    char buffer[NUM];
    while(true){
        sleep(2);
        buffer[0]=0;
        ssize_t n=read(rfd,buffer,sizeof(buffer));//读入文件到buffer里，读入大小为count和文件大小的最小值
        if(n>0){
            buffer[n]=0;
            cout<<"father get a message["<< getpid()<<"]#"<<buffer;
        }
    }
}

int main(){
    int pipefd[N]={0};
    int n=pipe(pipefd);
    if(n<0) return 1;
    //cout<<"pipefd[0]:"<<pipefd[0]<<" pipefd[1]:"<<pipefd[1]<<endl;
    
    pid_t id=fork();
    if(id<0) return 2;
    if(id==0){//子进程写入
        close(pipefd[0]);//关闭读入
        writer(pipefd[1]);

        close(pipefd[1]);
        exit(0);
    }
    close(pipefd[1]);//关闭写入
    reader(pipefd[0]);

    close(pipefd[0]);
    return 0;
}